const cache = require('./cache.js')
// wx.navigateTo 打开新页面
const navTo = (url = "", params = null, checkLogin = false) => {
  if (!url) return
  if (params) {
    params = encodeURIComponent(JSON.stringify(params))
  }
  if (checkLogin) {
    let UserInfo = cache.getUserInfo()
    if (!UserInfo) {
      wx.reLaunch({
        url: '/pages/login/index'
      })
    }
  }
  return new Promise((resolve, reject) => {
    wx.navigateTo({
      url: url + '?passData=' + params,
      success() {
        resolve()
      },
      fail(err) {
        reject(err)
      }
    })
  })
}
// wx.navigateBack 页面返回
const relBack = (url, params = null, checkLogin = false) => {
  if (!url) return
  if (params) {
    params = encodeURIComponent(JSON.stringify(params))
  }
  if (checkLogin) {
    let UserInfo = cache.getUserInfo()
    if (!UserInfo) {
      wx.reLaunch({
        url: '/pages/login/index'
      })
    }
  }
  return new Promise((resolve, reject) => {
    wx.navigateBack({
      url: url + '?passData=' + params,
      success() {
        resolve()
      },
      fail(err) {
        reject(err)
      }
    })
  })
}
// wx.switchTab Tab 切换
const swtTo = (url, checkLogin = false) => {
  if (!url) return
  if (checkLogin) {
    let UserInfo = cache.getUserInfo()
    if (!UserInfo) {
      wx.reLaunch({
        url: '/pages/login/index'
      })
    }
  }
  return new Promise((resolve, reject) => {
    wx.switchTab({
      url,
      success() {
        resolve()
      },
      fail(err) {
        reject(err)
      }
    })
  })
}
// wx.redirectTo 页面重定向
const redirTo = (url, params = null, checkLogin = false) => {
  if (!url) return
  if (params) {
    params = encodeURIComponent(JSON.stringify(params))
  }
  if (checkLogin) {
    let UserInfo = cache.getUserInfo()
    if (!UserInfo) {
      wx.reLaunch({
        url: '/pages/login/index'
      })
    }
  }
  return new Promise((resolve, reject) => {
    wx.redirectTo({
      url: url + '?passData=' + params,
      success() {
        resolve()
      },
      fail(err) {
        reject(err)
      }
    })
  })
}

// reLaunch 重启动
const relTo = (url, params = null, checkLogin = false) => {
  if (!url) return
  if (params) {
    params = encodeURIComponent(JSON.stringify(params))
  }
  if (checkLogin) {
    let UserInfo = cache.getUserInfo()
    if (!UserInfo) {
      wx.reLaunch({
        url: '/pages/login/index'
      })
    }
  }
  return new Promise((resolve, reject) => {
    wx.reLaunch({
      url: url + '?passData=' + params,
      success() {
        resolve()
      },
      fail(err) {
        reject(err)
      }
    })
  })
}


module.exports = {
  navTo,
  relBack,
  swtTo,
  redirTo,
  relTo,
}